package com.example.subscriber.recive;

import com.example.subscriber.config.SendPhoneMessagesConfig;
import com.example.utils.HttpUtils;
import com.example.utils.ValidateCodeUtils;
import com.example.utils.redis.RedisUtil;
import com.rabbitmq.client.Channel;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @project: kaoshi
 * @description:
 * @author: cjq
 * @create: 2022-11-06 21:33
 **/
@Component
public class SendPhoneMessageRecive {
    @Autowired
    RedisUtil redisUtil;
    private static final Logger log = LoggerFactory.getLogger(SendPhoneMessageRecive.class);

    @RabbitListener(queues = SendPhoneMessagesConfig.CJQ_SEND_PHONE_MESSAGE_QUEUE_NAME)
    public void revice(Message message, Channel channel){
        try {
            String phone = new String(message.getBody());
            String host = "https://gyytz.market.alicloudapi.com";
            String path = "/sms/smsSend";
            String method = "POST";
            String appcode = "d01938e3204c4c8ab6cdb4efc6b9cf4d";
            //生成随机数
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            if (StringUtils.isEmpty(redisUtil.get("code"))){
                redisUtil.set("code",code);
            }
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization", "APPCODE " + appcode);
            Map<String, String> querys = new HashMap<String, String>();
            querys.put("mobile", phone);
            querys.put("param", "**code**:"+ code +",**minute**:5");
            querys.put("smsSignId", "6668583b434e425192cbd0d12c8b09a8");
            querys.put("templateId", "6f2bcd3396884c33896724b0a0e06187");
            Map<String, String> bodys = new HashMap<String, String>();
            try {
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                System.out.println(response.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("我收到的消息是：{}", new String(message.getBody()));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
